from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import re
from django.views.generic import View
from django.core.cache import cache
from app.models import IndexTopCarousel, IndexBottomCarousel,IndexNewsBanner,ReceiverEmail,TopicType,Subtitle,SubtitleImage,SubtitleVideo
from utils.response_code import RET

# Create your views here.
# http://127.0.0.1:8000
# /
class IndexView(View):
    """首页英文"""
    def get(self, request):
        """显示"""
        # 尝试从缓存中获取数据
        #context = cache.get('index_page_data') # None pickle
        context = None

        if context is None:
            # 获取首页顶部轮播图信息
            print('设置首页缓存')
            top_carousel = ''
            bottom_carousel = ''
            news_banner = ''
            try:
                top_carousel = IndexTopCarousel.objects.all().order_by('index')[:2]


                # 获取首页底部轮播图信息

                bottom_carousel = IndexBottomCarousel.objects.all().order_by('index')[:2]

                # 获取首页新闻展示图片信息
                news_banner = IndexNewsBanner.objects.all().order_by('index')[:1]
            except Exception as e:
                print(e)

            # 缓存数据
            context = {
                'top_carousel': top_carousel,
                'bottom_carousel': bottom_carousel,
                'news_banner': news_banner
            }

            # 设置首页缓存
            # from django.core.cache import cache
            # cache.set('缓存名称', '缓存数据', '缓存有效时间'} pickle
            try:
                cache.set('index_page_data', context, 3600)
            except Exception as e:
                print(e)
        # 使用模板
        return render(request, 'index.html',context) # HttpResponse


class IndexCnView(View):
    """首页中文"""
    def get(self,request):
        # 尝试从缓存中获取数据
        # context = cache.get('index_page_data') # None pickle
        context = None

        if context is None:
            # 获取首页顶部轮播图信息
            print('设置首页缓存')
            top_carousel = ''
            bottom_carousel = ''
            news_banner = ''
            try:
                top_carousel = IndexTopCarousel.objects.all().order_by('index')[:2]

                # 获取首页底部轮播图信息

                bottom_carousel = IndexBottomCarousel.objects.all().order_by('index')[:2]

                # 获取首页新闻展示图片信息
                news_banner = IndexNewsBanner.objects.all().order_by('index')[:1]
            except Exception as e:
                print(e)

            # 缓存数据
            context = {
                'top_carousel': top_carousel,
                'bottom_carousel': bottom_carousel,
                'news_banner': news_banner
            }

            # 设置首页缓存
            # from django.core.cache import cache
            # cache.set('缓存名称', '缓存数据', '缓存有效时间'} pickle
            try:
                cache.set('index_page_data', context, 3600)
            except Exception as e:
                print(e)
            print('top',top_carousel)
        return render(request,'index_cn.html',context)

# http://127.0.0.1:8000/news
class NewsView(View):
    """新闻页"""
    def get(self,request):
        # 获取参数并判断参数是否存在
        language = request.GET.get('lang')
        index = request.GET.get('index')
        if not all([language,index]):
            return JsonResponse({'errno':RET.DATAERR,'errmsg':'请求参数不完整'})

        try:
            # 查询数据并判断数据是否为None
            news = IndexNewsBanner.objects.filter(language=language,index=index).first()
            if news is None:
                return JsonResponse({'errno':RET.NODATA,'errmsg':'数据不存在'})
        except Exception as e:
            return JsonResponse({'errno':RET.DBERR,'errmsg':'查询数据失败'})

        # 更新时间格式转换
        update_time = news.update_time.strftime("%Y-%m-%d %H:%M:%S")

        data = {
            'title':news.title,
            'content':news.content,
            'update_time':update_time
        }
        return JsonResponse({'errno':RET.OK,'errmsg':'返回数据成功','data':data})




# 127.0.0.1:8000/email
class EmailReceiveView(View):
    """获取用户输入的邮箱地址"""
    def post(self,request):
        email = request.POST.get('email')
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'errno':RET.DATAERR,'errmsg':'邮箱格式不正确'})
        try:
            email_obj = ReceiverEmail.objects.create()
            email_obj.email = email
            email_obj.save()
        except Exception as e:
            return JsonResponse({'errno':RET.THIRDERR,'errmsg':'保存邮箱失败'})
        return JsonResponse({'errno':RET.OK,'errmsg':'保存邮箱成功'})


# 127.0.0.1:8000/product_cn
class ProductCnView(View):
    """产品中心中文页面"""
    def get(self,request):
        topic_types = TopicType.objects.all().order_by('index')[:6]

        context = {
            'topic_types':topic_types
        }
        return render(request,'product_cn.html',context)


# 127.0.0.1:8000/product
class ProductView(View):
    """产品中心英文页面"""
    def get(self,request):
        topic_types = TopicType.objects.all().order_by('index')[:6]

        context = {
            'topic_types':topic_types
        }
        return render(request,'product.html',context)
